import traceback

from handlers.lib_handlers import necessary_params_check, optional_params_check, list_in_list_to_dict_in_list, \
    get_city_name
from submodules.common.lib.log_ import logger
from lib import http

from tools import mysql_

db_name = "house_information"
table_name = "court"
column_names = ['id', 'name', 'city_id', 'min_pricing_persqm', 'min_pricing', 'open_date', 'delivery_date',
                'sale_status',
                'court_address', 'property_management_type', 'decoration_type', 'property_rights', 'developer_name',
                'court_desc',
                'phone', 'source_type', 'created_at', 'updated_at', 'status']


def court_create(req):
    try:
        # necessary_param_list = ["name", "city_id"]
        res = http.Response()
        body = req.body

        # if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
        #                                       res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        key_list, value_list = [], []
        for k, v in body.items():
            key_list.append(k)
            value_list.append(v)
        value_list_with_quotes = ['"' + str(x) + '"' for x in value_list]
        sql = f'''INSERT INTO {db_name}.{table_name} ({",".join(key_list)}) VALUES ({",".join(value_list_with_quotes)});'''
        logger.info(sql)
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


def court_update_status(req):
    try:
        # necessary_param_list = ["id", "status"]
        res = http.Response()
        body = req.body

        # 参数校验
        # if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
        #                                       res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        id = body["id"]
        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET {",".join(optional_sql_str_list)} where id = {id};'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def court_modify(req):
    try:
        # optional_param_list = ["id", "name", "min_pricing"]
        res = http.Response()
        body = req.body
        try:
            body.__delitem__("city_name")
            body.__delitem__("limit")
        except:
            pass

        # 参数校验
        # if (res_tmp := optional_params_check(optional_param_list=optional_param_list, type="body", req=req,
        #                                      res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        id = body["id"]
        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET {",".join(optional_sql_str_list)} where id = {id};'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def court_list(req):
    try:
        # optional_param_list = ["id", "name", "status"]
        res = http.Response()
        body = req.body
        try:
            body.__delitem__("page")  # 前端无法去除 暂时保留传参，但不使用
            body.__delitem__("limit")
        except:
            pass

        # 参数校验
        # if (res_tmp := optional_params_check(optional_param_list=optional_param_list, type="body", req=req,
        #                                      res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql

        optional_sql_str = "WHERE "
        for k, v in body.items():
            if v != "":
                if k == "name":
                    optional_sql_str += f"{k} like '%{v}%' and "
                else:
                    optional_sql_str += f"{k}={v} and "
        if optional_sql_str == "WHERE ":
            optional_sql_str = ""
        else:
            optional_sql_str = optional_sql_str[:-4]
        sql = f'''SELECT * FROM {db_name}.{table_name} {optional_sql_str} ORDER BY updated_at DESC;'''
        logger.info(sql)

        # 执行sql
        res_sql = mysql_.select(sql)
        if res_sql[0] != False:
            res.code = 20000
            res.msg = "success"
            res.data = {}
            res.data["items"] = list_in_list_to_dict_in_list(res_sql[1], column_names)
            # 返回值添加city_name
            for i in range(len(res.data["items"])):
                city_name = get_city_name(res.data["items"][i]["city_id"])
                res.data["items"][i]["city_name"] = city_name
            res.data["total"] = len(res.data["items"])
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql[1]
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


if __name__ == "__main__":
    from lib.http import Request


    def test_court_create():
        req = Request()
        req.body = {
            "name": "han",
            "city_id": "122",
            "min_pricing": "10000"
        }
        res = court_create(req)
        print(res)


    def test_court_update_status():
        req = Request()
        req.body = {
            "id": "1",
            "status": "2"
        }
        res = court_update_status(req)
        print(res)


    def test_court_modify():
        req = Request()
        req.body = {
            "id": "1",
            "name": "北京北",
            "min_pricing": "20000"
        }
        res = court_modify(req)
        print(res)


    def test_court_list():
        req = Request()
        req.body = {
        }
        res = court_list(req)
        print(res)


    # test_court_create()
    # test_court_update_status()
    # test_court_modify()
    test_court_list()
